import { Component } from '@angular/core';
import { Observable, Scheduler } from 'rxjs/Rx';

import { Events, AlertController, NavParams, NavController, ToastController, Platform } from 'ionic-angular';
import { Storage } from '@ionic/storage';

import { BackgroundMode } from '@ionic-native/background-mode';
import { LocalNotifications } from '@ionic-native/local-notifications';

import { Config } from '../../providers/config';
import { MainPage } from '../main/main.component';
import { ContactListPage } from '../contact/list/list.component';
import { WorkIndexPage } from '../work/index/index.component';
import { SettingIndexPage } from '../setting/index/index.component';
import io from 'socket.io-client/dist/socket.io.js';
import { Common } from '../../providers/common';
import { TabsService } from './tabs.service';

import { InfoDetailPage } from '../info/detail/detail.component';

import { TaskDetailPage } from '../task/detail/detail.component';
import {GfrNetValuePage} from "../gfr/netvalue/netvalue.component";
import {BcwWarnPage} from "../bcw/warn/warn.component";
import { HttpClient } from '../../providers/httpClient';
import _ from "lodash";
import * as moment from "moment";
import {BcwHomeDetailPdfPage} from "../bcw/home/pdf.component";

@Component({
  templateUrl: 'tabs.html',
  providers: [TabsService]
})
export class TabsPage {
  //moa_page_name: any = "TabsPage";
  // set the root pages for each tab
  tab1Root: any = MainPage;
  tab2Root: any = WorkIndexPage;
  tab3Root: any = ContactListPage;
  tab4Root: any = SettingIndexPage;
  mySelectedIndex: number;


  constructor(
    public navParams: NavParams,
    public storage: Storage,
    public config: Config,
    public events: Events,
    public navCtrl: NavController,
    public common: Common,
    public alertCtrl: AlertController,
    public localNotifications: LocalNotifications,
    public platform: Platform,
    public backgroundMode: BackgroundMode,
    public toastCtrl: ToastController,
    public tabsService: TabsService,
    public httpClient: HttpClient
  ) {
    let that = this;

    setTimeout(function () {
      that.storage.get("errorMessage").then(function (errorMessage) {
        that.tabsService.syncLog(errorMessage).subscribe(result => {
          if (result) {
            console.log('-----------syncLog---------------');
            console.log(result);
            that.storage.set("errorMessage", []);
          }
        });
      });

      //上传用户行为数据
      that.tabsService.syncUserStatistics();
    }, 5000);

    /**
     * 定时上传用户行为数据
     */
    let timer = Observable.timer(0, 60 * 1000, Scheduler.queue);
    timer.subscribe(e => {
      // console.log("Observable.timer>>>>>>>>>>", moment().format("HH:mm") === "09:12");
      let current = moment().format("HH:mm");
      if (current == "00:00") {
        this.tabsService.syncUserStatistics();
      }
    });

    //
    this.storage.set("GfrNetValuePageIN",{v:"-1"});

    this.mySelectedIndex = navParams.data.tabIndex || 0;

    this.storage.get('contact-last-sync-time').then(lastSyncTime => {
      // 如果本地没有通讯录，则马上同步
      if (!lastSyncTime) {
        this.common.syncContactList('server', true);
      } else if (new Date().getTime() - lastSyncTime > this.config.autoSyncContactTime) {
        // 如果超过了配置好的时间，则自动刷新通讯录
        this.common.syncContactList('server', true);
      }
    });
    // 获取用户信息
    this.storage.get('userInfo').then(userInfo => {
      if (userInfo.seal) {
        let toast = this.toastCtrl.create({
          message: "预留印鉴：" + userInfo.seal,
          position: 'middle',
          duration: 2000,
          cssClass: "seal-background-color"
        });
        toast.present();
      }
    });

    // 建立长连接
    this.storage.get('id_token').then(token => {
      if (token) {

        //监听点击通知栏跳转页面
        this.events.unsubscribe("NotifyToGoPage");
        this.events.subscribe("NotifyToGoPage", (notification) => {
          let notificationData = JSON.parse(notification.data);
          if (notificationData.type === "gfr") {
            if (window.location.hash.indexOf("gfr/netvalue") > -1) {
              that.events.publish("GfrNetValuePage");
            } else {
              that.navCtrl.push(GfrNetValuePage);
            }
          } else {
            if (notificationData.type === "bcw") {
              if (window.location.hash.indexOf("bcw/warn") > -1) {
                that.events.publish("BcwWarnPageRefresh");
              } else {
                that.navCtrl.push(BcwWarnPage);
              }
            } else {

            }
          }
        });

        window['socketio'] = io(config.server, {
          // Send auth token on connection, you will need to DI the Auth service above
          'query': 'token=' + token
        });

        window['socketio'].on('connect', function () {
          console.info('---connnect----');
        });

        window['socketio'].on('push', function (data) {
          data = JSON.parse(data);
          // 如果是背景运行，才弹出提示
          console.log('---------push-----------');
          console.log(data);
          console.log(that.backgroundMode.isActive());
          if (that.platform.is('cordova') && that.backgroundMode.isActive()) {
            if (that.platform.is('android')) {
              that.localNotifications.schedule({
                id: new Date().getTime(),
                text: data.text,
                data: data.data
              });
            }
          } else {
            if (data.data.type === "gfr" || data.data.type === "bcw") {
              let gfrAlert = that.alertCtrl.create({
                title: '通知',
                subTitle: data.text,
                buttons: [{
                  text: '关闭',
                  role: 'cancel',
                  handler: () => {
                    //console.log('Cancel clicked');
                  }
                },
                  {
                    text: "查看",
                    handler: () => {
                      if (data.data.type === "gfr") {
                        if (window.location.hash.indexOf("gfr/netvalue") > -1) {
                          that.events.publish("GfrNetValuePage");
                        } else {
                          that.navCtrl.push(GfrNetValuePage);
                        }
                      }

                      if (data.data.type === "bcw") {
                        console.log(window.location.hash);
                        if (window.location.hash.indexOf("bcw/warn") > -1) {
                          that.events.publish("BcwWarnPageRefresh");
                        } else {
                          that.navCtrl.push(BcwWarnPage);
                        }
                      }
                    }
                  }]
              });
              gfrAlert.present();
            } else {
              let alert = that.alertCtrl.create({
                title: '通知',
                subTitle: data.text,
                buttons: ['确认']
              });
              alert.present();
            }
          }
          console.info('---push----');
        });
        window['socketio'].on('disconnect', function () {
          console.info('---disconnect--');
        });

      } else {

      }
    });

    // 绑定链接跳转事件
    this.events.unsubscribe('html-open-link:app');
    // 监听链接点击，跳转详情操作
    this.events.subscribe('html-open-link:app', (result) => {
      console.info(result);
      if (result.module == 'flow') {
        this.navCtrl.push(TaskDetailPage, {
          id: result.data.id
        })
      } else if (result.module == 'info') {
        this.navCtrl.push(InfoDetailPage, {
          fbbosid: result.data.id
        })
      } else {
        if (result.module === "bcw") {
          console.log("bcw link click >>>>>>>", result);
          this.navCtrl.push(BcwHomeDetailPdfPage, {
            url: result.data.url
          });
        }
      }
    });


    // 绑定文档里链接事件
    window['openDocLinked'] = function (url) {
      console.info('-------openDocLinked--------');
      that.common.checkUrl(url);
      return false;
    }

  }

}
